package com.rzico.sbl.ui.goods

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityGoodsBinding
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.model.GoodsData
import com.rzico.sbl.viewmodel.GoodsViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.slimadapter.SlimAdapter

class GoodsActivity : BaseActivity(R.layout.activity_goods) {

    private val mBinding by lazy { ActivityGoodsBinding.bind(getRootView()) }

    private val mKindList = arrayListOf<CommonData>()
    private val mCheckList = arrayListOf<String>()
    private var mKindId = ""
    private var mKindName = ""
    private var mKeyWord = ""
    private var mActionMode = ""

    override fun getViewModel() = get<GoodsViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        getKindData()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .emptyHint
                    .text = "暂无相关商品信息！"

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<GoodsData>(R.layout.item_goods_list) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_goods_name, bean.name)
                                text(R.id.item_goods_price, bean.price.formatDecimal())
                                text(R.id.item_goods_month, bean.monthSale)
                                text(
                                    R.id.item_goods_tag,
                                    bean.tags.joinToString("、") { it.name }
                                )

                                visibility(
                                    R.id.item_goods_tag,
                                    visibleValue { bean.tags.isNotEmpty() }
                                )

                                visibility(
                                    R.id.item_goods_has,
                                    visibleValue { bean.availableStock.intValue == 0 }
                                )

                                with<ImageView>(R.id.item_goods_check) {
                                    it.isVisible = mActionMode == "multiple"
                                    it.setImageResource(
                                        bean.check.conditionElseValue(
                                            actionTrue = { R.mipmap.login_yes_orange },
                                            actionFalse = { R.mipmap.login_no }
                                        )
                                    )
                                }

                                with<ImageView>(R.id.item_goods_logo) {
                                    it.loadImage(bean.thumbnail)
                                }

                                with<TextView>(R.id.item_goods_stock) {
                                    it.text = bean.availableStock
                                    it.setTextColor(
                                        getColorEx(
                                            conditionIf(
                                                bean.availableStock.intValue < 100,
                                                R.color.red,
                                                R.color.black
                                            )
                                        )
                                    )
                                }

                                clicked {
                                    when (mActionMode) {
                                        "single" -> {
                                            LiveEventBus
                                                .get("manualGoods")
                                                .post(bean)

                                            finishView()
                                        }

                                        "multiple" -> {
                                            bean.check.conditionElse(
                                                actionTrue = { mCheckList.remove(bean.productId) },
                                                actionFalse = { mCheckList += bean.productId }
                                            )

                                            bean.check = !bean.check
                                            notifyItemChanged(index)

                                            hintForSure()
                                        }

                                        else ->
                                            startActivityEx<GoodsEditActivity>(
                                                "itemId" to bean.id,
                                                "index" to index
                                            )
                                    }
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initTabLayout() {
        mBinding.goodsTab.apply {
            onTabSelectedListener {
                onTabSelected {
                    it?.let {
                        mKindId = mKindList[it.position].id
                        mKindName = mKindList[it.position].name.orEmpty()

                        getViewModel().cancelRequest()
                        getViewModel().delay { updateList() }
                    }
                }
            }

            mKindList.forEachIndexed { index, bean ->
                val kindId = intent.getExtra("kindId")
                addTab(
                    this.newTab().setText(bean.name),
                    conditionIf(
                        kindId.isNotEmpty(),
                        bean.id == kindId,
                        index == 0
                    )
                )
            }
        }
    }

    private fun initSearch() {
        mBinding
            .goodsSearch
            .apply {
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        (it.isEmpty() && mKeyWord.isNotEmpty())
                            .condition {
                                mKeyWord = ""
                                updateList()
                            }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    (actionId == EditorInfo.IME_ACTION_SEARCH)
                        .condition {
                            hideSoftInput() //隐藏软键盘

                            searchEdit.text.isBlank()
                                .conditionElse(
                                    actionTrue = { showToast("请输入关键字") },
                                    actionFalse = {
                                        mKeyWord = searchEdit.textTrim
                                        updateList()
                                    }
                                )
                        }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit.text.isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入关键字") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    override fun initListener() {
        mBinding.apply {
            // 选择商品模式
            mActionMode =
                intent.getExtra("mode")
                    .also {
                        when (it) {
                            "single" -> {
                                goodsKind.gone()
                                goodsBottom.gone()
                            }

                            "multiple" -> {
                                goodsKind.gone()
                                goodsBottom.visible()

                                intent
                                    .getExtra("productIds")
                                    .notEmpty {
                                        mCheckList.addItems(split(","))
                                    }

                                hintForSure()
                            }
                        }
                    }

            goodsCancel.oneClick { finishView() }

            goodsSure.oneClick {
                mCheckList.ifEmpty {
                    showToast(intent.getExtra("hint"))
                    return@oneClick
                }

                // 记账商品、自提商品刷新
                LiveEventBus
                    .get("goodsMultiple")
                    .post(mCheckList.joinToString(","))

                finishView()
            }
        }

        // 商品编辑观察
        observe<String>("productList") { result ->
            val items = result.split(",")
            when (items[0]) {
                "delete" -> {
                    items[1].intValue.also {
                        mList.removeAt(it)
                        mAdapter.notifyDataSetChanged()
                    }
                }

                "refresh" -> updateList()
            }
        }
    }

    private fun hintForSure() {
        mBinding
            .goodsSure
            .text = "确定(${mCheckList.size})"
    }

    /**
     * 商品分类
     */
    private fun getKindData() {
        getViewModel()
            .productCat()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mKindList.apply {
                        clear()
                        add(CommonData(name = "全部"))
                        addItems(it)
                    }

                    initTabLayout()
                }
            )
    }

    /**
     * 商品列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .productList(
                page = index,
                kindId = mKindId,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    (mActionMode == "multiple")
                        .condition {
                            mList.forEach {
                                it as GoodsData
                                it.check = it.productId in mCheckList
                            }
                        }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}